import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {
    FooterToolbar,
    ModalForm,
    PageContainer,
    ProFormText,
    ProFormTextArea,
    ProTable,
    ProFormDateRangePicker,
    ProFormDigit,
    ProFormUploadButton,
    ProFormSelect,
    ProFormRadio,
    ProFormDateTimePicker,
    ProFormList,
} from '@ant-design/pro-components';
import {Button, Drawer, Input, message, Modal, Tag, Badge, Space, Statistic, Row, Col} from 'antd';
import React, {useRef, useState} from 'react';
import type {NetworkListItem} from './data';
import {networkList, networkAdd, networkEdit, networkSelectList, networkDelete} from './service';
import {dataCenterSelectList} from "@/pages/power/data-center-list/service";
import {HostComputerOrderStatusEnum, NetworkConnTypeEnum} from "@/pages/data.enum";
import AddNetworkModalForm from "@/pages/power/network/add";
import {organizationResourceRecycle} from "@/pages/organization/resource-manager/service";
import {organizationSelectList} from "@/pages/organization/org-list/service";
import {HostComputerListItem} from "@/pages/power/host-computer/list/data";
import {skuSelectList} from "@/pages/power/sku/sku-list/service";
import {Link} from "react-router-dom";
import {NetworkHostComputerListItem} from "./data";

const {confirm} = Modal;

export type FormValueType = {
    target?: string;
    template?: string;
    type?: string;
    time?: string;
    frequency?: string;
} & Partial<NetworkListItem>;


const handleUpdate = async (fields: FormValueType, currentRow?: NetworkListItem) => {
    const hide = message.loading('正在配置');

    try {
        await networkEdit({
            ...currentRow,
            ...fields,
        });
        hide();
        message.success('配置成功');
        return true;
    } catch (error) {
        hide();
        message.error('配置失败请重试！');
        return false;
    }
};


const handleRemove = async (selectedRows: NetworkListItem[]) => {
    const hide = message.loading('正在回收');
    if (!selectedRows) return true;

    try {
        await organizationResourceRecycle({
            orderIds: selectedRows.map((row) => row.orderId),
        });
        hide();
        message.success('回收成功，即将刷新');
        return true;
    } catch (error) {
        hide();
        message.error('回收失败，请重试');
        return false;
    }
};


const networkHostComputerColumns: ProColumns<NetworkHostComputerListItem>[] = [
    {
        title: '所属资源池',
        dataIndex: "dataCenterName",
        valueType: 'text',
        search: false,
        ellipsis: true, // 关闭自动换行
    },
    {
        title: '主机名称',
        dataIndex: 'hostComputerName',
        search: true,
        ellipsis: true, // 关闭自动换行
    },
    {
        title: '规格',
        dataIndex: "skuName",
        search: false,
        valueType: 'text',
        ellipsis: true, // 关闭自动换行
    },

    {
        title: '机房编号',
        dataIndex: 'machineRoomNo',
        search: true,
        ellipsis: true, // 关闭自动换行
    },
    {
        title: '机柜编号',
        dataIndex: 'cabinetNo',
        search: true,
        ellipsis: true, // 关闭自动换行
    },
];


const NetworkList: React.FC = () => {
    /** 新建窗口的弹窗 */
    const [createModalVisible, handleCreateModalVisible] = useState<boolean>(false);
    /** 分布更新窗口的弹窗 */
    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
    const [networkHostComputerModalVisible, handleNetworkHostComputerModalVisible] = useState<boolean>(false);
    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<NetworkListItem>();
    const [selectedRowsState, setSelectedRows] = useState<NetworkListItem[]>([]);

    /** 国际化配置 */
    const columns: ProColumns<NetworkListItem>[] = [
        {
            title: '订单ID',
            dataIndex: "orderId",
            valueType: 'text',
            search: false,
            hidden: true,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '所属资源池',
            dataIndex: "dataCenterId",
            valueType: 'select',
            search: true,
            hidden: true,
            ellipsis: true, // 关闭自动换行
            request: async () => {
                const result = await dataCenterSelectList({});
                return (
                    result.data?.map((item) => ({
                        label: item.name,
                        value: item.dataCenterId,
                    })) || []
                );
            },
        },
        {
            title: '所属资源池',
            dataIndex: "dataCenterName",
            valueType: 'text',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '关联租户',
            dataIndex: "organizationName",
            valueType: 'text',
            search: false,
            ellipsis: true, // 关闭自动换行
        },

        {
            title: '网络ID',
            dataIndex: 'networkId',
            search: false,
            hidden: true,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '网络名称(备注)',
            dataIndex: 'networkName',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '连接类型',
            dataIndex: 'connType',
            search: true,
            valueType: 'select',
            valueEnum: NetworkConnTypeEnum,
            width: 80,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '互联网IP',
            dataIndex: 'publicIp',
            search: true,
            width: 80,
            ellipsis: true, // 关闭自动换行
            render: (value, record, index) => {
                let result = [];
                for (let i = 0; i < record.publicIpList?.length; i++) {
                    let s = record.publicIpList[i].publicIp
                    if (record.publicIpList[i].port != '') {
                        s  = s + " 端口:" + record.publicIpList[i].port
                    }
                    if (record.publicIpList[i].bandwidth != 0) {
                        s  = s + " 带宽:" + record.publicIpList[i].bandwidth + "M"
                    }
                    result.push(
                        <div key={i}>
                            {s}
                            {i < record.publicIpList.length - 1 && <br/>}
                        </div>
                    );
                }
                return <div>{result}</div>;
            },
        },
        {
            title: '共享带宽',
            dataIndex: 'topology',
            search: false,
            ellipsis: true, // 关闭自动换行
            render: (value, record, index) => {
                if (record.bandwidth > 0) {
                    return <span>{record.bandwidth}M</span>
                } else {
                    return '-'
                }
            }
        },
        {
            title: '关联主机',
            dataIndex: 'hostComputerList',
            search: false,
            width: 120,
            ellipsis: true, // 关闭自动换行
            render: (value, record, index) => {
                if (record.hostComputerList?.length > 0) {
                    return <a
                        key="hostComputerList"
                        onClick={() => {
                            setCurrentRow(record);
                            handleNetworkHostComputerModalVisible(true);
                        }}
                    >
                        查看
                    </a>
                } else {
                    return ''
                }
            }
        },
        {
            title: '计费周期',
            dataIndex: "orderInfo",
            valueType: 'text',
            search: false,
            ellipsis: true, // 关闭自动换行
            width: 80,
        },
        {
            title: '开通时间',
            dataIndex: "createdAt",
            valueType: 'text',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            fixed: 'right',
            ellipsis: true, // 关闭自动换行
            render: (_, record) => {
                return [
                    <a
                        key="config"
                        onClick={() => {
                            handleUpdateModalVisible(true);
                            setCurrentRow(record);
                        }}
                    >
                        编辑
                    </a>,
                ]
            },
        },
    ];

    return (
        <PageContainer>
            <ProTable<NetworkListItem, API.ListPagination>
                headerTitle="网络列表"
                actionRef={actionRef}
                rowKey="orderId"
                search={{
                    labelWidth: 90,
                }}
                toolBarRender={() => [
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            handleCreateModalVisible(true);
                        }}
                    >
                        <PlusOutlined/> 开通
                    </Button>,
                ]}
                scroll={{x: true}}
                request={networkList}
                columns={columns}
                rowSelection={{
                    onChange: (_, selectedRows) => {
                        setSelectedRows(selectedRows);
                    },
                }}
                options={{
                    density: true,
                    fullScreen: true,
                    reload:true,
                    setting: false
                }}
            />
            {selectedRowsState?.length > 0 && (
                <FooterToolbar
                    extra={
                        <div>
                            已选择{' '}
                            <a
                                style={{
                                    fontWeight: 600,
                                }}
                            >
                                {selectedRowsState.length}
                            </a>{' '}
                            项 &nbsp;&nbsp;
                        </div>
                    }
                >
                    <Button
                        onClick={async () => {
                            confirm({
                                title: '回收并删除网络配置',
                                content: '回收并删除网络网络配置前，请确认网络配置关联的资源已清除，是否现在删除?',
                                onOk() {
                                    handleRemove(selectedRowsState);
                                    setSelectedRows([]);
                                    actionRef.current?.reloadAndRest?.();
                                    return true;
                                }
                            });
                        }}
                    >
                        批量回收
                    </Button>
                </FooterToolbar>
            )}

            <AddNetworkModalForm
                modalVisible={createModalVisible}
                onClose={() => {
                    handleCreateModalVisible(false);
                }}
                onSuccess={() => {
                    if (actionRef.current) {
                        actionRef.current.reload();
                    }
                }}
            />

            <ModalForm
                title="编辑网络信息"
                width="650px"
                open={updateModalVisible}
                onVisibleChange={handleUpdateModalVisible}
                onFinish={async (value) => {
                    const success = await handleUpdate(value, currentRow);
                    if (success) {
                        handleUpdateModalVisible(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                modalProps={{destroyOnClose: true}}
                rowProps={{
                    gutter: [20, 0],
                }}
                initialValues={{
                    networkId: currentRow?.networkId,
                    networkName: currentRow?.networkName,
                    publicIpList: currentRow?.publicIpList,
                    // bandwidth: currentRow?.bandwidth,
                    connType: currentRow?.connType,
                    topology: currentRow?.topology,
                    dataCenterName: currentRow?.dataCenterName,
                    organizationName: currentRow?.organizationName,
                    orderInfo: currentRow?.orderInfo,
                }}
            >
                <ProFormText
                    name="resourceType"
                    label="资源类型"
                    disabled={true}
                    hidden={true}
                />
                <Row>
                    <Col span={8}>
                        <Space>
                            <ProFormText
                                label="资源池"
                                name="dataCenterName"
                                width={200}
                                disabled={true}
                            />
                        </Space>
                    </Col>

                    <Col span={8} offset={4}>
                        <Space>
                            <ProFormText
                                label="租户"
                                name="organizationName"
                                style={{width: 200}}
                                colProps={{
                                    span: 8,
                                }}
                                disabled={true}
                            />
                        </Space>
                    </Col>
                </Row>
                <Row>
                    <Col span={20}>
                        <Space>
                            <ProFormText
                                name="networkName"
                                label="网络名称(备注)"
                                width={"md"}
                                rules={[{required: true, message: '请输入网络名称(备注)'}]}
                            />
                        </Space>
                    </Col>
                </Row>
                <Row>
                    <Col span={20}>
                        <Space>
                            <ProFormSelect
                                name="connType"
                                label="连接类型"
                                valueEnum={NetworkConnTypeEnum}
                                width={"md"}
                                disabled={true}
                            />
                        </Space>
                    </Col>
                </Row>


                {currentRow?.connType === 'internet' && (<ProFormList
                        name="publicIpList"
                        initialValue={[{publicIp: ''}]}
                        creatorButtonProps={{
                            position: 'bottom',
                            creatorButtonText: '添加一个互联网IP',
                        }}
                    >
                        <Row>
                            <Col span={8}>
                                <ProFormText
                                    width={"md"}
                                    name="publicIp"
                                    label="互联网IP"
                                />
                            </Col>
                            <Col span={4} offset={2}>
                                <ProFormText
                                    width={"md"}
                                    name="port"
                                    label="端口"
                                />
                            </Col>
                            <Col style={{textAlign: 'right'}} span={4} offset={2}>
                                <ProFormDigit
                                    name="bandwidth"
                                    label="带宽"
                                    width={150}
                                    fieldProps={
                                        {addonAfter: 'M'}
                                    }
                                />
                            </Col>
                        </Row>
                    </ProFormList>
                )}

                {/*<ProFormTextArea*/}
                {/*    name="topology"*/}
                {/*    label="网络拓扑"*/}
                {/*/>*/}

            </ModalForm>

            <Modal
                title="关联主机信息"
                width="650px"
                open={networkHostComputerModalVisible}
                // onVisibleChange={handleNetworkHostComputerModalVisible}
                onOk={() => handleNetworkHostComputerModalVisible(false)}
                onCancel={() => handleNetworkHostComputerModalVisible(false)}
                // okText="确认"
                // cancelText="取消"
            >
                <ProTable<NetworkListItem, API.ListPagination>
                    rowKey="hostComputerName"
                    search={false}
                    toolBarRender={() => []}
                    scroll={{x: true}}
                    columns={networkHostComputerColumns}
                    rowSelection={false}
                    options={false}
                    dataSource={currentRow?.hostComputerList}
                />
            </Modal>
        </PageContainer>
    );
};

export default NetworkList;
